package org.beginningee6.book.chapter02;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import java.util.*;

/**
 * @author Antonio Goncalves APress Book - Beginning Java EE 6 with Glassfish
 *         http://www.apress.com/ http://www.antoniogoncalves.org --
 */
public class Main {

  public static void main(String[] args) {

    System.out.println("Starting ...");
    
    // Creates an instance of book
    System.out.println("Creating a new Book instance");
    Book book = new Book();
    book.setTitle("The Hitchhiker's Guide to the Galaxy");
    book.setPrice(12.5F);
    book.setDescription("Science fiction comedy series created by Douglas Adams.");
    book.setIsbn("1-84023-742-2");
    book.setNbOfPage(354);
    book.setIllustrations(false);

    // Gets an entity manager and a transaction
    System.out.println("Getting EntityManagerFactory");
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("chapter02PU");
    System.out.println("Getting EntityManager");
    EntityManager em = emf.createEntityManager();

    // Persists the book to the database
    System.out.println("Persisting the Book");
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    em.persist(book);
    tx.commit();

    // Retrieves all the books from the database
    List<Book> books = em.createNamedQuery("findAllBooks").getResultList();

    System.out.println("Retrieving values from Database");
    for(Book b : books){
      System.out.println("\t" + b);
    }
    
    em.close();
    emf.close();
    
    System.out.println("Done.");
  }
}